const User = require('../models/userModel');
const WebSocketConnection = require('../models/websocketModel');

const register = (req, res) => {
  const { username, password } = req.body;

  // 校验用户名和密码是否为空
  if (!username || !password) {
    return res.status(400).json({ error: 'Username and password are required' });
  }

  User.create(username, password, function(err) {
    if (err) {
      return res.status(400).json({ error: 'Username already exists' });
    }
    res.status(201).json({ message: 'User registered successfully' });
  });
};

const login = (req, res) => {
  const { username, password } = req.body;

  // 校验用户名和密码是否为空
  if (!username || !password) {
    console.error('Username or password is missing');
    return res.status(400).json({ error: 'Username and password are required' });
  }

  console.log(`Login attempt for user ${username}`);

  User.findByUsername(username, function(err, user) {
    if (err) {
      console.error('Database error:', err);
      return res.status(500).json({ error: 'Database error' });
    }
    if (!user) {
      console.log(`User ${username} not found`);
      return res.status(401).json({ error: 'Invalid credentials' });
    }
    if (user.password !== password) {
      console.log(`Incorrect password for user ${username}`);
      return res.status(401).json({ error: 'Invalid credentials' });
    }

    console.log(`User ${username} logged in successfully`);

    // 更新用户状态为 online
    User.updateStatus(user.id, 'online', (err) => {
      if (err) {
        console.error(`Error updating status for user ${user.id}:`, err);
        return res.status(500).json({ error: 'Database error' });
      }
      console.log(`User ${user.id} status updated to online`);

      // 记录 WebSocket 连接
      const connectionId = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
      WebSocketConnection.addConnection(user.id, connectionId, (err) => {
        if (err) {
          console.error(`Error saving WebSocket connection for user ${user.id}:`, err);
          return res.status(500).json({ error: 'Database error' });
        }
        console.log(`WebSocket connection for user ${user.id} stored in database`);
        res.json({ message: 'Login successful', userId: user.id });
      });
    });
  });
};

const logout = (req, res) => {
  const { userId } = req.body;

  if (!userId) {
    return res.status(400).json({ error: 'User ID is required' });
  }

  // 更新用户状态为 offline
  User.updateStatus(userId, 'offline', (err) => {
    if (err) {
      console.error(`Error updating status for user ${userId}:`, err);
      return res.status(500).json({ error: 'Database error' });
    }
    console.log(`User ${userId} status updated to offline`);
    res.json({ message: 'Logout successful' });
  });
};

module.exports = { register, login, logout }; 